from app.database.postgre import SessionDep, col
from app.database.models import Account, App, TrialRecord
from app.models import responses
from app.models.common import TrialRecordIdJSON
from app.models.trial_records import AppTrialRecordListParams, UpdateTrialCountJSON


async def get_trial_records_list(
        account: Account,
        query_params: AppTrialRecordListParams,
        session: SessionDep
):
    """获取筛选后的试用记录"""
    # 构建查询参数
    app_id = query_params.app_id
    page = query_params.page
    page_size = query_params.page_size
    device_code = query_params.device_code
    trial_ip = query_params.trial_ip

    # 获取查询的应用
    app = session.get(App, query_params.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 创建筛选条件
    query = session.query(TrialRecord).filter(TrialRecord.app_id == app_id).order_by(col(TrialRecord.id).desc())

    if device_code:
        query = query.filter(col(TrialRecord.device_code).like(f"%{device_code}%"))

    if trial_ip:
        query = query.filter(col(TrialRecord.trial_ip).like(f"%{trial_ip}%"))

    # 获取筛选后的总数
    total_count = query.count()
    total_pages = (total_count + page_size - 1) // page_size

    # 对筛选后的数据进行分页
    offset = (page - 1) * page_size
    paginated_query = query.offset(offset).limit(page_size)
    paginated_records = paginated_query.all()

    return responses.SuccessResponse(
        data={
            'total': total_count,
            'total_pages': total_pages,
            'page': page,
            'page_size': len(paginated_records),
            'list': [record.model_dump() for record in paginated_records]
        }
    )


async def delete_trial_record(account: Account, json_data: TrialRecordIdJSON, session: SessionDep):
    """删除试用记录"""
    # 获取对应的应用
    app_id = json_data.app_id
    app = session.get(App, app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 获取被删除的记录
    record = session.get(TrialRecord, json_data.record_id)
    if not record or record.app_id != app_id:
        return responses.Response703()

    session.delete(record)
    session.commit()

    return responses.SuccessResponse(msg='试用记录已删除', data=record.model_dump(include={'id'}))


async def update_record_trial_count(account: Account, json_data: UpdateTrialCountJSON, session: SessionDep):
    """更新记录中的已试用次数"""
    # 获取对应的应用
    app_id = json_data.app_id
    app = session.get(App, app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 获取被修改的记录
    record = session.get(TrialRecord, json_data.record_id)
    if not record or record.app_id != app_id:
        return responses.Response703()

    record.trial_count = json_data.trial_count
    session.commit()
    session.refresh(record)
    return responses.SuccessResponse(data=record.model_dump(include={'id', 'trial_count'}))
